package com.sunlands.deskmate.service.impl;

import com.alibaba.fastjson.JSON;
import com.sunlands.deskmate.client.DeskMateGroupService;
import com.sunlands.deskmate.dto.RequestDTO;
import com.sunlands.deskmate.entity.TzChatRecord;
import com.sunlands.deskmate.message.enums.MessageType;
import com.sunlands.deskmate.mapper.TzChatRecordMapper;
import com.sunlands.deskmate.service.MessageService;
import com.sunlands.deskmate.vo.GroupUserVO;
import com.sunlands.deskmate.vo.TzChatRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lishuai
 */
@Service("messageService")
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    private TzChatRecordMapper messageMapper;

    @Autowired
    private DeskMateGroupService deskMateGroupService;

    @Override
    public String sendMessage(TzChatRecord message) {
        log.info("【" + message.getFromUserId() + ": " + message.getMessage() + "】");
        String str = null;
        try {
            str = JSON.toJSONString(message);
//            redisTemplate.convertAndSend(queue, str);
        } catch (Exception e) {
            log.error("method sendMessage error !" + e);
        }
        return str;
    }

    @Override
    public List<TzChatRecordVO> findUnreadRecord(RequestDTO requestDTO) {
        List<TzChatRecord> chatRecords = new ArrayList<>();;
        if (MessageType.PRIVATE_CHAT.getType().equals(requestDTO.getType())) {
            chatRecords = messageMapper.selectPrivateChatRecord(requestDTO);
        } else if (MessageType.GROUP_CHAT.getType().equals(requestDTO.getType())) {
            GroupUserVO groupUser = deskMateGroupService.getGroupUser(requestDTO.getDestId(), requestDTO.getUserId()).getData();
            if (Objects.nonNull(groupUser) && Objects.nonNull(groupUser.getCreateTime())) {
                requestDTO.setEnterTime(DateFormatUtils.format(groupUser.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            }
            chatRecords = messageMapper.selectGroupChatRecord(requestDTO);
        } else if (MessageType.ROOM_CHAT.getType().equals(requestDTO.getType())) {
            chatRecords = messageMapper.selectRoomChatRecord(requestDTO);
        }
        return chatRecords.stream().map(TzChatRecordVO::from).collect(Collectors.toList());
    }

    @Override
    public int saveChatRecord(TzChatRecord record) {
        return messageMapper.insertSelective(record);
    }

    @Override
    public List<TzChatRecord> selectRecentChatRecord(String userId) {
        return messageMapper.selectRecentChatRecord(userId);
    }

}
